package org.demo.five;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author  
 * @date    2010-10-26
 * @file    org.demo.five.SemApp.java
 */
public class SemApp {
	public static void main(String[] args) {
		Runnable limitedCall = new Runnable(){
			final Random rand = new Random();
			final Semaphore available = new Semaphore(3);
			int count = 0;
			@Override
			public void run() {
				int time = rand.nextInt(10);
				int num = count++;
				// 
				try {
					available.acquire();
					System.out.println("Long-running action for " + time + " seconds.. #" + num);
					Thread.sleep(TimeUnit.SECONDS.toMillis(time));
					System.out.println("Done with # " + num);
					available.release();
				} catch(Exception e){
					e.printStackTrace();
				}
				
			}
		};
		for (int i=0; i<10; i++){
			new Thread(limitedCall).start();
		}
	}
}
